// @ts-nocheck
import axios from "axios";
import {ElMessage, ElMessageBox, ElNotification, ElLoading} from "element-plus";

//axios默认访问地址
axios.defaults.baseURL = "http://localhost:8080/";
//axios默认 content-type 可以不用配置
axios.defaults.headers.post["Content-Type"] = "application/json;charset=UTF-8";

//配置数据加载等待效果
const loading = (() => {
    let loadingInstance = null;
    return {
        show(text) {
            loadingInstance = ElLoading.service({
                lock: true,
                text,
                background: "rgba(0, 0, 0, 0.4)",
            });
        },
        close() {
            loadingInstance.close();
        },
    };
})();

/**
 * request 拦截
 */
axios.interceptors.request.use(
    config => {
        if (sessionStorage.getItem("token")) {
            config.headers.Authorization = 'Bearer ' + sessionStorage.getItem("token");
        }
        loading.show("加载中");
        return config;
    },
    error => {
        ElMessage.error({
            message: "加载超时",
        });
        Promise.reject(error);
    }
);

/**
 * response 拦截
 */
//预留接口：1、判断自定义的各种错误。2、自定义错误提示信息。
const responseStatusHandler = {
    404: () => {  //重写系统错误
        ElNotification.error({
            title: "错误",
            message: "404访问地址不存在",
        });
    },
    401: () => { //自定义异常
        ElNotification.error({
            title: "错误",
            message: "用户未登录，请先登录！",
        });
    },
};
axios.interceptors.response.use(
    response => {
        loading.close();
        return response;
    },
    error => {
        loading.close();
        // 默认除了2XX之外的都是错误的，就会走这里
        if (error.response) {
            const {status} = error.response;
            const handlerFunc = responseStatusHandler[status];
            if (handlerFunc) handlerFunc();
            else {
                ElMessage.error({
                    title: error.status,
                    message: error.response.data.msg || error.response.data.message || error.message,
                });
            }
        }
        return Promise.reject(error);
    }
);

export default axios;
